package com.code.generator.builder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.code.generator.ExceputionUtils;
import com.code.generator.GeneratorConstants;
import com.code.generator.GeneratorUtils;
import com.code.generator.entity.ColumnsEntity;
import com.code.generator.entity.TableEntity;
import com.code.view.entity.HandlerVO;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


/**
 * 创建实体类，包括注释信息
 *
 * @author 朱国军
 * @version 2014年8月25日 朱国军
 */
public class EntityBuilder extends BaseBuilder {

    @Override
    public boolean builder(TableEntity tableEntity, String packagePath, HandlerVO handlerVO, Configuration cfg) {
        try {
            createEntity(tableEntity, packagePath, cfg, handlerVO);
            createParam(tableEntity, packagePath, cfg, handlerVO);
        } catch (IOException e) {
            ExceputionUtils.logging("生成实体类时IO异常", e);
            return false;
        } catch (TemplateException e) {
            ExceputionUtils.logging("生成实体类时模版异常", e);
            return false;
        } catch (Exception e) {
            ExceputionUtils.logging("生成实体类时其他异常", e);
            return false;
        }
        return true;
    }


    /**
     * 实体类创建方法
     *
     * @param tableEntity 数据库表对象
     * @param packagePath 包路径
     * @param author 作者
     * @param cfg 模版配置对象
     * @throws IOException IO异常
     * @throws TemplateException 模版异常
     */
    private void createEntity(TableEntity tableEntity, String packagePath, Configuration cfg, HandlerVO handlerVO) throws IOException,
            TemplateException {

        /* 获取或创建一个模版 */
        Template temp = cfg.getTemplate("Entity.ftl", "UTF-8");

        Map<String, Object> dataMap = getDataMap(tableEntity, packagePath, handlerVO);
        dataMap.put("imports", createImport(tableEntity.getColumnsEntitys()));

        String filePath = handlerVO.getOutPutPath() + GeneratorUtils.getFilePath(packagePath)+ "/entity/" + tableEntity.getClassName() + handlerVO.getEntitySuffix() + ".java";
        GeneratorUtils.witeFile(filePath, temp, dataMap);

    }


    /**
     * 查询实体类创建方法
     *
     * @param tableEntity 数据库表对象
     * @param packagePath 包路径
     * @param author 作者
     * @param cfg 模版配置对象
     * @throws IOException IO异常
     * @throws TemplateException 模版异常
     */
    private void createParam(TableEntity tableEntity, String packagePath, Configuration cfg, HandlerVO handlerVO) throws IOException,
            TemplateException {

        /* 获取或创建一个模版 */
        Template temp = cfg.getTemplate("Param.ftl", "UTF-8");
        Map<String, Object> dataMap = getDataMap(tableEntity, packagePath, handlerVO);
        dataMap.put("imports", createParamImport(tableEntity.getColumnsEntitys()));
        dataMap.put("columns", getParamColumns(tableEntity.getColumnsEntitys()));

        String filePath = handlerVO.getOutPutPath() +GeneratorUtils.getFilePath(packagePath)+  "/param/" + tableEntity.getClassName() + "Param.java";
        GeneratorUtils.witeFile(filePath, temp, dataMap);

    }


    private List<String> createImport(List<ColumnsEntity> columnsEntitys) {
        List<String> imports = new ArrayList<String>(200);
        Map<String, Integer> numMap = new HashMap<String, Integer>();
        for (ColumnsEntity columnsEntity : columnsEntitys) {
            if (StringUtils.isNotBlank(columnsEntity.getFullType()) && null == numMap.get(columnsEntity.getFullType())) {
                imports.add(columnsEntity.getFullType());
                numMap.put(columnsEntity.getFullType(), 1);
            }
        }
        return imports;
    }


    private List<String> createParamImport(List<ColumnsEntity> columnsEntitys) {
        List<String> imports = new ArrayList<String>(200);
        Map<String, Integer> numMap = new HashMap<String, Integer>();
        for (ColumnsEntity columnsEntity : columnsEntitys) {
            if (StringUtils.isNotBlank(columnsEntity.getFullType()) && null == numMap.get(columnsEntity.getFullType())
                    && StringUtils.contains(GeneratorConstants.PARAM_TYPE, columnsEntity.getFullType())) {
                imports.add(columnsEntity.getFullType());
                numMap.put(columnsEntity.getFullType(), 1);
            }
        }
        return imports;
    }


    private List<ColumnsEntity> getParamColumns(List<ColumnsEntity> columns) {
        List<ColumnsEntity> paramColumns = new ArrayList<ColumnsEntity>();
        for (ColumnsEntity column : columns) {
            if (StringUtils.contains(GeneratorConstants.PARAM_TYPE, column.getFullType())) {
                ColumnsEntity paramColumnStart = new ColumnsEntity();
                paramColumnStart.setColumnName(column.getColumnName() + GeneratorConstants.TIME_PREFIX);
                paramColumnStart.setColumnSize(column.getColumnSize());
                paramColumnStart.setIsNullAble(column.getIsNullAble());
                paramColumnStart.setIsPrimary(column.getIsPrimary());
                paramColumnStart.setRemark(column.getRemark() + "开始时间");
                paramColumnStart.setTypeName(column.getTypeName());
                paramColumns.add(paramColumnStart);

                ColumnsEntity paramColumnEnd = new ColumnsEntity();
                paramColumnEnd.setColumnName(column.getColumnName() + GeneratorConstants.TIME_SUFFIX);
                paramColumnEnd.setColumnSize(column.getColumnSize());
                paramColumnEnd.setIsNullAble(column.getIsNullAble());
                paramColumnEnd.setIsPrimary(column.getIsPrimary());
                paramColumnEnd.setRemark(column.getRemark() + "结束时间");
                paramColumnEnd.setTypeName(column.getTypeName());
                paramColumns.add(paramColumnEnd);
            }
        }
        return paramColumns;
    }
}
